package com.javaweb.common;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;

public class StringTool {
    public static final String UTF = "UTF-8" ;
    private static final String SEP = "&" ;

    /**
     * decode in url encoding in UTF-8
     * @param org
     * @return
     */
    public static String URLEncodeInUTF(String org) {
        try {
            return URLEncoder.encode(org, UTF);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null ;
    }

    public static String URLDecodeInUTF(String org) {
        try {
            return URLDecoder.decode(org, UTF);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null ;
    }
    public static boolean isEmpty(String str) {
        return str == null || "".equals(str.trim()) ;
    }

    public static boolean isEmpty(String ... strs) {
        for (String str : strs) {
            if (isEmpty(str)) {
                return true ;
            }
        }

        return false ;
    }

    public static String formatTime(Date time) {
        String sdf = "yyyy-MM-dd HH:mm:ss SSS" ;
        SimpleDateFormat format = new SimpleDateFormat(sdf) ;
        return format.format(time) ;
    }
    public static String formatDouble(double value) {
        return String.format("%.1f", value) ;
    }
    public static int parseToInt(String numeric) {
        return Integer.parseInt(numeric) ;
    }

    /**
     * encoding the contents.
     * @param contents
     * @return
     */
    public static String encrypt(String ...contents) {
        String salt = "hello" ;
        StringBuilder stringBuilder = new StringBuilder() ;

        for (String cont : contents) {
            stringBuilder.append(cont) ;
            stringBuilder.append(SEP) ;
        }
        stringBuilder.append(salt) ;
        System.out.println("[StringTool] got encoded:" + stringBuilder.toString()) ;
        return URLEncodeInUTF(stringBuilder.toString()) ;
    }

    public static String[] decry(String orgText) {
        if (isEmpty(orgText)) return null ;
        return URLDecodeInUTF(orgText).split(SEP) ;
    }


}
